package com.thirteenClassicsServer.controller;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.thirteenClassics.constant.JwtClaimsConstant;
import com.thirteenClassics.dto.UserLoginDTO;
import com.thirteenClassics.entity.User;
import com.thirteenClassics.properties.JwtProperties;
import com.thirteenClassics.result.Result;
import com.thirteenClassics.utils.JwtUtil;
import com.thirteenClassics.vo.UserLoginVO;
import com.thirteenClassicsServer.service.IUserService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @Resource
    private JwtProperties jwtProperties;


    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录：{}", userLoginDTO);

        User user = userService.login(userLoginDTO);


        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, user.getUid());
        claims.put(JwtClaimsConstant.LANG, user.getLang());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);


        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getUid())
                .userName(user.getUsername())
                .email(user.getEmail())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 退出
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success("成功，前端需要删除本地token");
    }


}
